package com.huoshan.im.server.listener;

import com.alibaba.fastjson.JSON;
import com.huoshan.im.server.ContextNaming;
import lombok.extern.slf4j.Slf4j;
import online.chazi.netkit.Session;
import online.chazi.netkit.channel.NetkitChannelEvent;
import online.chazi.netkit.listener.NetkitChanelListener;
import online.chazi.netkit.messaging.Message;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicInteger;


/**
 * 说明：作者很懒，什么都没留下
 * Created by 火山九日 on 2020-04-26 09:25
 */
@Slf4j
@Component
public class ChannelListener implements NetkitChanelListener {

    public void onRegistered(NetkitChannelEvent netkitChannelEvent) {
        log.debug("onRegistered");
    }

    public void onUnregistered(NetkitChannelEvent netkitChannelEvent) {
        log.debug("onUnregistered");
    }

    public void onExceptionCaught(NetkitChannelEvent netkitChannelEvent, Throwable throwable) {
        log.error(throwable.getMessage(), throwable);
        //todo 是否发生异常时，关闭。根据业务来定
        //举个例子，当累计发生3次异常，则主动关闭连接。
        Session session = netkitChannelEvent.getServerContext().getSession(netkitChannelEvent.getChannel());
        AtomicInteger errCount = (AtomicInteger) session.getAttribute(ContextNaming.CHANNEL_EXCEPTION_CAUGHT_COUNT);
        if (errCount.get() > 2) {
            netkitChannelEvent.getChannel().close();
        } else {
            int i = errCount.incrementAndGet();
            if (i > 2) {
                netkitChannelEvent.getChannel().close();
            }
        }
    }

    public void onMessageReceived(NetkitChannelEvent netkitChannelEvent, Message message) {
        log.debug("收到消息:{}, content:{}", JSON.toJSONString(message), JSON.toJSONString(new String(message.getMessageContent())));
    }

}
